import { Redis, RedisOptions } from 'ioredis'
import { Injectable } from '@nestjs/common'
import { CoreCacheService, CoreCacheServiceOption } from '../core-cache.service'

@Injectable()
export class CoreCacheRedisService extends CoreCacheService {
  readonly redisClient: Redis

  // 过期时间，单位:秒
  static readonly EXPIRE = 60 * 60 * 24

  constructor(option: RedisOptions & CoreCacheServiceOption) {
    super(option)

    this.redisClient = new Redis(option)
  }

  get(key: string): Promise<string | null> {
    return this.redisClient.get(this.makeKey(key))
  }

  set(key: string, data: string): Promise<void> {
    return this.redisClient.set(this.makeKey(key), data, 'EX', CoreCacheRedisService.EXPIRE).then()
  }

  del(key: string): Promise<void> {
    return this.redisClient.del(this.makeKey(key)).then()
  }

  clear(): Promise<void> {
    return Promise.resolve()
  }

  has(key: string): Promise<boolean> {
    return this.redisClient.get(this.makeKey(key)).then(data => data != null && data === '')
  }

  createNSService(namespace: string): CoreCacheService {
    return new CoreCacheRedisService({
      ...this.option,
      namespace,
    })
  }
}
